<template>
  <PageWrapper>
    <BasicTable
      @register="registerTable"
      :rowSelection="
        checkboxShow
          ? {
              type: 'checkbox',
              columnWidth: 44,
              selectedRowKeys: checkedDelKeys,
              onChange: onSelectChange,
              getCheckboxProps: onGetCheckboxProps
            }
          : null
      "
    >
      <template #tableTitle>
        <a-space :size="12">
          <a-button v-auth="permissionCodeMap.goodsAdd" type="primary" @click="operateUser(operateActionType.ADD)"
            >新增商品</a-button
          >
          <a-button v-auth="permissionCodeMap.goodsDel" :disabled="!checkedDelKeys.length" danger @click="operateDel"
            >批量删除</a-button
          >
        </a-space>
      </template>

      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'packageNameSet'">
          <div v-if="text && text.length">
            {{ text.join('、') }}
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operate'">
          <a-button
            type="link"
            v-auth="permissionCodeMap.goodsView"
            class="g-operate-btn"
            @click="operateUser(operateActionType.VIEW, record)"
            >查看</a-button
          >
          <a-button
            type="link"
            v-if="record.userId !== currentUserId"
            class="g-operate-btn"
            v-auth="permissionCodeMap.goodsEdit"
            @click="operateUser(operateActionType.EDIT, record)"
            >编辑</a-button
          >
        </template>
      </template>
    </BasicTable>
    <GoodsAdd @register="goodsAddRegister" @operateSuccess="operateSuccess" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch, createVNode, onMounted } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import { BasicTable, useTable } from '@/components/Table'
import { getGoodsBasicColumns, getSearchFormConfig } from './dataSource'
import { useDrawer } from '@/components/Drawer'
import { useModal } from '@/components/Modal'
import GoodsAdd from './components/GoodsAdd.vue'
import { userStore } from '@/store/modules/user'
import { permissionCodeMap } from '@/utils/permissionCodeMap'
import { operateActionType, operateTxtType, constantMap } from '@/types/enum'
import { ProductRecord } from '@/types/goods'
import EllipsisTooltip from '@/components/EllipsisTooltip/index.vue'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'
import { toEleTreeData } from '@/utils'
import { cloneDeep } from 'lodash-es'
import api from '@/api'
const { goodsQueryPage, goodsDel, goodsAuthority } = api

const userModule = userStore()

const currentUserId = computed(() => userModule.userInfo?.userId)
const checkboxShow = computed(() => userModule.permissionActionList.includes(permissionCodeMap.goodsDel))

const [registerTable, { reload, setPagination }] = useTable({
  api: goodsQueryPage,
  columns: getGoodsBasicColumns(),
  useSearchForm: true,
  formConfig: getSearchFormConfig(),
  showIndexColumn: true,
  rowKey: 'id',
  scroll: { y: constantMap.tableYHeight, x: '100%' }
})

const [goodsAddRegister, { openDrawer: GoodsAddOpenDrawer, setDrawerProps }] = useDrawer()

const checkedDelKeys = ref<Array<string | number>>([])
const goodsData = reactive<any>({
  originAuthority: [],
  authority: []
})

const onSelectChange = (selectedRowKeys: (string | number)[], selectedRow: ProductRecord[]) => {
  checkedDelKeys.value = selectedRowKeys
}
const operateSuccess = () => {
  setPagination({
    current: 1
  })
  reload()
}

const getGoodsAuthority = async () => {
  let res = await goodsAuthority()
  let result = cloneDeep(res.result) || []
  if (result && result.length) {
    result.forEach((item: any) => {
      if (item.authorityList && item.authorityList.length) {
        item.authorityList = toEleTreeData(item.authorityList)
      }
    })
  }
  goodsData.originAuthority = cloneDeep(res.result)
  goodsData.authority = result
}

onMounted(() => {
  getGoodsAuthority()
})
// 禁止删除已绑定套餐的商品
const onGetCheckboxProps = (record: ProductRecord) => {
  return {
    disabled: record.packageNameSet && record.packageNameSet.length > 0
  }
}
// 批量删除
const operateDel = () => {
  Modal.confirm({
    title: '确定批量删除所选商品？',
    centered: true,
    icon: createVNode(ExclamationCircleFilled),
    content: `删除后数据不可恢复`,
    autoFocusButton: null,
    class: 'modal-confirm-box',
    async onOk() {
      await goodsDel({
        idSet: checkedDelKeys.value
      })
      message.success(`删除成功`)
      operateSuccess()
    },
    onCancel() {}
  })
}
const operateUser = (type: OperateType, record?: ProductRecord) => {
  setDrawerProps({
    title: operateTxtType[type] + '商品',
    showOkBtn: type !== operateActionType.VIEW,
    cancelText: type === operateActionType.VIEW ? '关闭' : '取消'
  })
  GoodsAddOpenDrawer(true, {
    type,
    record,
    authority: goodsData.authority,
    originAuthority: goodsData.originAuthority
  })
}
</script>

<style lang="less" scoped></style>
